﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using Analysis.DAL.Repositories;
using System.Configuration;

namespace Analysis
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["IsDevelopmentEnvironment"])) return;

            string userName = "";
            if (Membership.GetUser() != null)
                userName = Membership.GetUser().UserName;

            System.Exception ex = Server.GetLastError();
            try
            {
                DataAccess.ExecuteSQL(string.Format(@"insert into Log([EventMessage], [StackTrace], [CurrentUser], [Path], [QueryString], [Browser], [UserHostAddress], [UrlReferrer])
                values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
                    (ex.InnerException != null ? ex.InnerException.Message : ex.Message).Replace("'", "''"),
                    (ex.InnerException != null ? ex.InnerException.StackTrace : ex.StackTrace).Replace("'", "''"),
                    userName,
                    Context.Request.Path.Replace("'", "''"),
                    Context.Request.QueryString.ToString(),
                    Context.Request.Browser.Browser,
                    Context.Request.UserHostAddress,
                    (Context.Request.UrlReferrer != null ? Context.Request.UrlReferrer.ToString() : "")
                ));

                Response.Write("Произошла неожиданная ошибка. Подробнее в журнале. ");
                Server.ClearError();
            }
            catch (Exception exNew)
            {
                Response.Write("Unexpected error occurs (" + ex.Message + " -> " + exNew.Message + ")<br/>" + ex.StackTrace);
                Server.ClearError();
            }
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
